<?php

namespace Trois\Crontab;

use App\HttpController\Open\Mini;
use App\Model\AdMiniProgramModel;
use EasySwoole\Component\Singleton;
use EasySwoole\Crontab\JobInterface;
use EasySwoole\EasySwoole\Core;
use EasySwoole\EasySwoole\Logger;
use Trois\Lib\Help;

/**
 * 检测小程序状态
 */
class SendMiniStatueCrontab implements JobInterface
{
    use Singleton;

    public function jobName(): string
    {
        return "SendMiniStatueCrontab";
    }

    public function crontabRule(): string
    {
        return '*/5 * * * *';
    }

    public function run(): void
    {
        $this->handle();
    }

    public function handle(): bool
    {

        Logger::getInstance()->info("开始处理 SendMiniStatueCrontab");

        $where['status'] = 1;
        $where['type'] = 1;
//        $where['create_time'] = strtotime(date('Y-m-d', strtotime("-2 day")));

        $minis = Help::modelInvoke(AdMiniProgramModel::class, function ($model) use ($where) {
            return $model->field('id,app_id,bra_id')->where($where)->limit(200)->order('id', 'DESC')->all();
        });

        $datas = [];

        foreach ($minis as $mini) {
            $datas[] = $mini['id'];
            $datas[] = $mini['app_id'] . '-' . $mini['id'] . '-' . $mini['bra_id'];
        }

        Logger::getInstance()->info("开始处理 SendMiniStatueCrontab success:" . count($minis) / 2);

        \EasySwoole\RedisPool\RedisPool::invoke(function (\EasySwoole\Redis\Redis $redis) use ($datas) {
            $datas && $redis->zAdd(Mini::$key, ...$datas);
        });

        return true;
    }


    public function onException(\Throwable $throwable)
    {
        Logger::getInstance()->error("SendMiniStatueCrontab onException:" + $throwable->getMessage());
    }

}